package com.warmlight.voicepacket;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.base.BaseActivity;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.ui.Add2NetListActivity;
import com.warmlight.voicepacket.utils.FileUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.TimeFormatUtils;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class TextToVoiceActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_content;
    private Button bt_make;
    private Button bt_add;

    //语音合成对象
    private SpeechSynthesizer mTts;
    //语音发声人
    private String voicer = "xiaoyan";
    //缓冲进度
    private int mPercentForBuffering = 0;
    // 播放进度
    private int mPercentForPlaying = 0;
    // 引擎类型
    private String mEngineType = SpeechConstant.TYPE_CLOUD;

    private String oldPath;
    private String newPath;
    private String name = "tts.wav";
    private RecyclerView recyclerView;
    private String text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_text_to_voice);
        initView();
        initData();
        initListener();
        showDialog();
    }


    private void showDialog() {
        boolean aBoolean = SPUtils.getBoolean(SPUtils.TEXT2VOICE);
        if (!aBoolean){
            AlertDialog alertDialog = new AlertDialog.Builder(getContext())
                    .setTitle("功能使用条款")
                    .setMessage("1. 在用户遵守用户使用条款及隐私策略（可在[我的]界面下查看）的前提下，本产品授予用户关于本产品有限的、不可转让的、非独占的、可撤销的、仅为个人  用途的非商业性的使用的权利。\n" +
                            " 2. 为保证传播内容的合法性，使用本产品生产制作的内容会上传审核，若发现违规内容则此条内容将不可使用\n" +
                            " 3. 玩皮语音保留本使用条款未特别授予的所有权利")
                    .setCancelable(false)
                    .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //埋点
                            MobclickAgent.onEvent(getContext(), MobClickHelper.TXTOSPEECH_TERM_YES);
//                HashMap<String, Object> temp = new HashMap<>();
//                temp.put("登录返回", "");
                            ZhugeSDK.getInstance().track(getContext(), MobClickHelper.TXTOSPEECH_TERM_YES);
                            dialog.dismiss();
                            SPUtils.putBoolean(SPUtils.TEXT2VOICE,true);
                        }
                    }).create();

            alertDialog.show();

        }
    }

    private void start(){
        //这里防止用户连击造成问题
        String s = bt_make.getText().toString();
        if (TextUtils.equals("点击开始转化",s) || TextUtils.equals("开始制作",s)){

        }else {
            return;
        }
        deleteFile();
        bt_make.setText("正在合成音频");
        text = et_content.getText().toString();
        if (text.isEmpty()) {
            showToast("请先输入文字");
            return;
        }
//        name = TimeFormatUtils.getCurrentTimeMillis() + ".wav";
        mTts = SpeechSynthesizer.createSynthesizer(getThis(), mTtsInitListener);
    }

    /**
     * 返回时删除文件
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        deleteFile();
    }

    private void deleteFile(){
        if (!TextUtils.isEmpty(newPath)){
            FileUtils.deleteFile(newPath);
        }
    }

    private void initListener() {
        bt_make.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start();
//                String text = et_content.getText().toString();
//                if (text.isEmpty()) {
//                    showToast("请先输入文字");
//                    return;
//                }
//                name = text + ".wav";
//                mTts = SpeechSynthesizer.createSynthesizer(getThis(), mTtsInitListener);
//                mTts.startSpeaking(text, mTtsListener);
            }
        });

        bt_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (FileUtils.isFileExists(oldPath)) {
                    long time = TimeFormatUtils.getCurrentTimeMillis();
                    String recordFile = FileUtils.getRecordFile(getContext());
                    name = time + ".wav";
                    newPath = recordFile + "/" + name;
                    // 循环判断直到生成可用的副本名
                    while (FileUtils.isFileExists(newPath)) {
                        //重命名重名定义规范--Util.getCopyNameFromOriginal(String)-自定义方法：根据自定义规则生成原名称副本
                        newPath = FileUtils.getCopyNameFromOriginal(newPath);
                    }
                    FileUtils.copyFile(oldPath, newPath);

//                    String recordFile = FileUtils.getRecordFile(getThis());
//                    File file1 = new File(recordFile,file.getName());
//                    FileUtils.copyFile(lastRecordFile,file1.getAbsolutePath());

                    RecommendFeed.DataBean.ListBean bean = new RecommendFeed.DataBean.ListBean();
                    bean.setId(time+"");
                    try {
                        bean.setCover_name(TimeFormatUtils.longToString(time,"yyyy年MM月dd日HH时mm分ss秒")+"制作");
                    } catch (ParseException e) {
                        e.printStackTrace();
                        String nm = name;
                        nm = nm.replace(".wav","");
                        bean.setCover_name(nm);
                    }
                    String title = text;
                    if (TextUtils.isEmpty(title)){
                        title = bean.getCover_name();
                    }
//                    title = title.replace(".wav","");
                    bean.setTitle(title);

                    bean.setUrl(newPath);
                    bean.setType("1");
                    Intent intent = new Intent(getContext(), Add2NetListActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mine_audio",bean);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }else {
                    showToast("添加失败");
                }



            }
        });
        et_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)){
                    bt_add.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void initData(){
        oldPath = FileUtils.TTS_PATH + "tts.wav";
        FileUtils.mkdirPath(oldPath);
        String[] voice_name = new String[]{"粤语女声","川音女声","河南男声","陕西女声","普通话女","东北女声","女声童音","蜡笔小新"};
        String[] voice = new String[]{"vixm","vixr","vixk","vixying","xiaoyan","xiaoqian","vinn","vixx"};
        final ArrayList<Map<String,String>> data = new ArrayList<>();
        for(int i=0;i<voice_name.length;i++){
            Map<String,String> map = new HashMap<>();
            map.put("voice_name",voice_name[i]);
            map.put("voice",voice[i]);
            if (voice[i].equals("xiaoyan")){
                map.put("select","1");
            }else {
                map.put("select", "0");
            }
            data.add(map);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(gridLayoutManager);
        RcvAdapter adapter = new RcvAdapter(this,data);
        adapter.setCallBack(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String, String> map = data.get(position);
                String voice1 = map.get("voice");
                voicer = voice1;
                if (mTts != null && mTts.isSpeaking()){
                    mTts.stopSpeaking();
                    mTts.destroy();
                }
                start();
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void initView(){
        LinearLayout ll_back = (LinearLayout) findViewById(R.id.ll_back);
        ll_back.setOnClickListener(this);
        et_content = (EditText) findViewById(R.id.et_content);
        bt_make = (Button) findViewById(R.id.bt_make);
        bt_add = (Button) findViewById(R.id.bt_add);
        bt_add.setVisibility(View.INVISIBLE);
        recyclerView = (RecyclerView) findViewById(R.id.rcv_voice);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
        }
    }

    /**
     * 初始化监听
     */
    private InitListener mTtsInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            // TODO Auto-generated method stub
            if (code != ErrorCode.SUCCESS) {
                showToast("语音合成失败,错误码: " + code);
                bt_make.setText("开始制作");//防止出错的时候无法再次点击
            } else {
                setParam();
                String text = et_content.getText().toString();
                code = mTts.startSpeaking(text, mTtsListener);
                if (code != ErrorCode.SUCCESS) {
                    if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) {
                        //未安装则跳转到提示安装页面
                        //  mInstaller.install();
                    } else {
                        showToast("语音合成失败,错误码: " + code);
                    }
                    bt_make.setText("开始制作");//防止出错的时候无法再次点击
                }
            }
        }
    };

    /**
     * 设置参数
     */
    private void setParam() {
        // 清空参数
        mTts.setParameter(SpeechConstant.PARAMS, null);
        // 根据合成引擎设置相应参数
        if (mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
            // 设置在线合成发音人
            mTts.setParameter(SpeechConstant.VOICE_NAME, voicer);
            //设置合成语速
            mTts.setParameter(SpeechConstant.SPEED, "30");//mSharedPreferences.getString("speed_preference", "50")
            //设置合成音调
            mTts.setParameter(SpeechConstant.PITCH, "50");//mSharedPreferences.getString("pitch_preference", "50")
            //设置合成音量
            mTts.setParameter(SpeechConstant.VOLUME, "100");//mSharedPreferences.getString("volume_preference", "50")
        } else {
            mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
            // 设置本地合成发音人 voicer 为空，默认通过语记界面指定发音人。
            mTts.setParameter(SpeechConstant.VOICE_NAME, "");
            /**
             * TODO 本地合成不设置语速、音调、音量，默认使用语记设置
             * 开发者如需自定义参数，请参考在线合成参数设置
             */
        }
        //设置播放器音频流类型
        mTts.setParameter(SpeechConstant.STREAM_TYPE, "3");// mSharedPreferences.getString("stream_preference", "3")
        // 设置播放合成音频打断音乐播放，默认为true
        mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

        // 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
        // 注：AUDIO_FORMAT参数语记需要更新版本才能生效
        mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
        mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, oldPath);
    }

    /**
     * 合成回调监听
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
//            showToast("开始播放");
        }

        @Override
        public void onSpeakPaused() {
//            showToast("暂停播放");
        }

        @Override
        public void onSpeakResumed() {
//            showToast("继续播放");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
            mPercentForBuffering = percent;
            bt_make.setText("正在制作：" + mPercentForBuffering + "%");
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
            mPercentForPlaying = percent;
            bt_make.setText("正在播放：" + mPercentForPlaying + "%");
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                // 播放完成
                bt_make.setText("开始制作");
                mTts.destroy();
                bt_add.setVisibility(View.VISIBLE);
            } else {
                showToast(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //  if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //      String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //      Log.d(TAG, "session id =" + sid);
            //  }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if( null != mTts ){
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }
    }

    static class RcvAdapter extends RecyclerView.Adapter<MyViewHolder>{
        private Context mContext;
        private ArrayList<Map<String,String>> mData = new ArrayList<>();
        public RcvAdapter(Context context, ArrayList<Map<String, String>> data){
            this.mContext = context;
            this.mData = data;
        }

        private AdapterView.OnItemClickListener clickListener;
        private void setCallBack(AdapterView.OnItemClickListener callBack){
            this.clickListener = callBack;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.view_voicetype_list,parent,false);
            MyViewHolder viewHolder = new MyViewHolder(view);
            return viewHolder;
        }

        /**
         * map.put("voice_name",voice_name[i]);
         map.put("voice",voice[i]);
         map.put("select","0");
         String[] voice_name = new String[]{"粤语女声","川音女声","河南男声","陕西女声","普通话女","女声英文","女声童音","蜡笔小新"};
         String[] voice = new String[]{"vixm","vixr","vixk","vixying","xiaoyan","catherine","vinn","vixx"};
         * @param holder
         * @param position
         */
        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position) {
            Map<String, String> map = mData.get(position);
            String voice_name = map.get("voice_name");
            String voice = map.get("voice");
            String select = map.get("select");
            holder.tv_voice_name.setText(voice_name);
            if ("0".equals(select)){
                if ("vixm".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixm_n);
                }else if ("vixr".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixr_n);
                }else if ("vixk".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixk_n);
                }else if ("vixying".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixying_n);
                }else if ("xiaoyan".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.xiaoyan_n);
                }else if ("xiaoqian".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.xiaoqian_n);
                }else if ("vinn".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vinn_n);
                }else if ("vixx".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixx_n);
                }
            }else{
                if ("vixm".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixm_y);
                }else if ("vixr".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixr_y);
                }else if ("vixk".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixk_y);
                }else if ("vixying".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixying_y);
                }else if ("xiaoyan".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.xiaoyan_y);
                }else if ("xiaoqian".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.xiaoqian_y);
                }else if ("vinn".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vinn_y);
                }else if ("vixx".equals(voice)){
                    holder.iv_voice_img.setImageResource(R.drawable.vixx_y);
                }
            }

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    select(position);
                }
            });
        }

        private void select(int position){
            Map<String, String> map = mData.get(position);
            if ("1".equals(map.get("select"))){
                return;
            }
            if (clickListener != null){
                clickListener.onItemClick(null,null,position,position);
            }
            for (int i=0;i<getItemCount();i++){
                mData.get(i).put("select","0");
            }
            mData.get(position).put("select","1");
            notifyDataSetChanged();
        }


        @Override
        public int getItemCount() {
            return mData == null ? 0 : mData.size();
        }
    }

    static class MyViewHolder extends RecyclerView.ViewHolder{
        ImageView iv_voice_img;
        TextView tv_voice_name;
        public MyViewHolder(View itemView) {
            super(itemView);
            iv_voice_img = (ImageView) itemView.findViewById(R.id.iv_voice_img);
            tv_voice_name = (TextView) itemView.findViewById(R.id.tv_voice_name);
        }
    }
}
